#!/bin/bash

# Caddy 服务管理脚本
# 使用方法: ./caddy.sh [run|stop|init]

CADDY_BIN="/opt/index/caddy_linux_amd64"
CADDYFILE="/opt/index/Caddyfile"
SERVICE_NAME="welcome.service"
SERVICE_SOURCE="./${SERVICE_NAME}"
SERVICE_TARGET="/usr/lib/systemd/system/${SERVICE_NAME}"
WORKING_DIR="/opt/index"

# 检查参数数量
if [ $# -ne 1 ]; then
    echo "Usage: $0 [run|stop|init]"
    exit 1
fi

case "$1" in
    "init")
        # 检测当前目录是否有welcome.service文件
        if [ ! -f "$SERVICE_SOURCE" ]; then
            echo "Creating $SERVICE_SOURCE..."
            
            # 创建welcome.service文件
            cat > "$SERVICE_SOURCE" << EOF
[Unit]
Description=Welcome Service (Caddy Web Server)
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=$WORKING_DIR
ExecStart=$CADDY_BIN run --config $CADDYFILE --adapter caddyfile
ExecReload=/bin/kill -s HUP \$MAINPID
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
EOF
            
            echo "Service file created at $SERVICE_SOURCE"
        else
            echo "Service file already exists at $SERVICE_SOURCE"
        fi
        
        # 创建软链接到系统目录
        if [ ! -L "$SERVICE_TARGET" ] && [ ! -f "$SERVICE_TARGET" ]; then
            echo "Creating symlink to $SERVICE_TARGET"
            ln -s "$(realpath $SERVICE_SOURCE)" "$SERVICE_TARGET"
            # 重新加载systemd配置
            systemctl daemon-reload
            # 开启自启服务
            systemctl enable "$SERVICE_NAME"
            echo "Symlink created and systemd reloaded"
        else
            echo "Service already exists in systemd directory, skipping symlink creation"
        fi
        ;;
        
    "run")
        # 启动服务
        systemctl start "$SERVICE_NAME"
        systemctl status "$SERVICE_NAME" --no-pager -l
        ;;
        
    "stop")
        # 停止服务
        systemctl stop "$SERVICE_NAME"
        ;;
        
    *)
        echo "Error: Unknown argument '$1'"
        echo "Usage: $0 [run|stop|init]"
        exit 1
        ;;
esac

exit 0